<template>
  <div class="order-system">
    <!-- 顶部标题和选项卡 -->
    <div class="header">
      <el-tabs v-model="activeTab" class="main-tabs">
        <el-tab-pane label="点餐服务" name="order"></el-tab-pane>
        <el-tab-pane label="订单列表" name="orderList"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 点餐服务模块 -->
      <div v-show="activeTab === 'order'" class="order-service">
        <div class="order-container">
          <!-- 左侧菜品分类和菜品列表 -->
          <div class="left-panel">
            <div class="category-list">
              <div
                  v-for="category in mealGroups"
                  :key="category.id"
                  :class="['category-item', { 'active': currentCategory === category.id }]"
                  @click="currentCategory = category.id"
              >
                {{ category.name }}
              </div>
            </div>

            <div class="dish-list">
              <div class="search-bar">
                <el-input
                    v-model="searchKeyword"
                    placeholder="请输入..."
                    clearable
                    @clear="handleSearchClear"
                    @keyup.enter="handleSearch"
                >
                  <template #append>
                    <el-button icon="el-icon-search" @click="handleSearch" />
                  </template>
                </el-input>
              </div>

              <div class="screen-control">
                <el-button size="small" @click="prevScreen">上—屏</el-button>
                <el-button-group>
                  <el-button size="small" icon="el-icon-arrow-up" @click="scrollUp"></el-button>
                  <el-button size="small" icon="el-icon-arrow-down" @click="scrollDown"></el-button>
                </el-button-group>
                <span class="screen-number">↑{{ currentScreen }}</span>
                <el-button size="small" @click="nextScreen">下—屏</el-button>
              </div>

              <div class="meals">
                <div v-for="dish in filteredDishes" :key="dish.id" class="dish-item">
                  <div class="dish-info">
                    <div class="dish-name">{{ dish.name }}</div>
                    <div class="dish-price">￥{{ dish.price.toFixed(2) }}</div>
                  </div>
                  <el-button
                      type="primary"
                      size="small"
                      @click="addToCart(dish)"
                  >
                    添加
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧已选菜单和结算 -->
          <div class="right-panel">
            <div class="selected-meals">
              <div class="panel-header">
                <span>已选菜单</span>
                <el-button type="text" @click="clearCart">清空</el-button>
              </div>
              <div class="dish-cart">
                <div v-for="(item, index) in cart" :key="index" class="cart-item">
                  <div class="cart-dish-info">
                    <span class="dish-name">{{ item.dish.name }}</span>
                    <span class="dish-quantity">×{{ item.quantity }}份</span>
                  </div>
                  <div class="cart-dish-price">￥{{ (item.dish.price * item.quantity).toFixed(2) }}</div>
                  <div class="cart-dish-actions">
                    <el-button
                        size="mini"
                        icon="el-icon-minus"
                        @click="decreaseQuantity(index)"
                    ></el-button>
                    <el-button
                        size="mini"
                        icon="el-icon-plus"
                        @click="increaseQuantity(index)"
                    ></el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete"
                        @click="removeFromCart(index)"
                    ></el-button>
                  </div>
                </div>
              </div>
            </div>

            <div class="order-summary">
              <div class="summary-item">
                <span>总计数量：</span>
                <span>×{{ totalQuantity }}份</span>
              </div>
              <div class="summary-item">
                <span>总计金额：</span>
                <span>￥{{ totalAmount.toFixed(2) }}</span>
              </div>
              <div class="summary-item">
                <span>菜品折扣：</span>
                <span>￥{{ discountAmount.toFixed(2) }}</span>
              </div>
              <div class="dish-remark">
                <el-input
                    v-model="orderRemark"
                    type="textarea"
                    :rows="2"
                    placeholder="菜品备注"
                ></el-input>
              </div>
              <el-button
                  type="primary"
                  class="checkout-btn"
                  :disabled="cart.length === 0"
                  @click="showCheckoutDialog"
              >
                下单并结账
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单列表模块 -->
      <div v-show="activeTab === 'orderList'" class="order-list">
        <el-tabs v-model="orderStatus" class="order-tabs">
          <el-tab-pane label="新订单" name="new"></el-tab-pane>
          <el-tab-pane label="制作中" name="preparing"></el-tab-pane>
          <el-tab-pane label="配送中" name="delivering"></el-tab-pane>
          <el-tab-pane label="已完成" name="completed"></el-tab-pane>
          <el-tab-pane label="待支付" name="pendingPayment"></el-tab-pane>
        </el-tabs>

        <div class="orders">
          <div v-for="order in filteredOrders" :key="order.id" class="order-item">
            <div class="order-header">
              <span class="order-id">订单编号：{{ order.orderNumber }}</span>
              <span class="order-status">{{ getStatusText(order.status) }}</span>
            </div>

            <div class="order-meals">
              <span>菜单：</span>
              <span>{{ formatDishes(order.meals) }}</span>
            </div>

            <div class="order-details">
              <div class="detail-item">
                <span>菜单数量：</span>
                <span>{{ order.totalQuantity }}</span>
              </div>
              <div class="detail-item">
                <span>取餐方式：</span>
                <span>{{ order.pickupMethod === 'dineIn' ? '堂食' : `配送（${order.deliveryAddress}）` }}</span>
              </div>
              <div class="detail-item">
                <span>支付方式：</span>
                <span>{{ getPaymentMethodText(order.paymentMethod) }}</span>
              </div>
            </div>

            <div class="order-amount">
              <div class="amount-item">
                <span>订单金额：</span>
                <span>￥{{ order.totalAmount.toFixed(2) }}</span>
              </div>
              <div class="amount-item">
                <span>折扣金额：</span>
                <span>￥{{ order.discountAmount.toFixed(2) }}</span>
              </div>
              <div class="amount-item">
                <span>实付金额：</span>
                <span>￥{{ order.actualAmount.toFixed(2) }}</span>
              </div>
              <div class="amount-item">
                <span>下单时间：</span>
                <span>{{ order.orderTime }}</span>
              </div>
            </div>

            <div v-if="order.remark" class="order-remark">
              <span>订单备注：</span>
              <span>{{ order.remark }}</span>
            </div>

            <div class="order-actions">
              <el-button
                  v-if="order.status === 'new'"
                  size="small"
                  @click="cancelOrder(order.id)"
              >
                取消订单
              </el-button>
              <el-button
                  v-if="order.status === 'new'"
                  type="primary"
                  size="small"
                  @click="acceptOrder(order.id)"
              >
                接单
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下单结账对话框 -->
    <el-dialog
        title="确认支付"
        v-model="checkoutDialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <div class="checkout-dialog">
        <div class="order-details">
          <div class="detail-item">
            <span>订单金额：</span>
            <span>￥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="detail-item">
            <span>下单时间：</span>
            <span>{{ currentTime }}</span>
          </div>
        </div>

        <div class="pickup-method">
          <span>取餐方式：</span>
          <el-radio-group v-model="pickupMethod">
            <el-radio label="dineIn">堂食</el-radio>
            <el-radio label="delivery">配送</el-radio>
          </el-radio-group>
        </div>

        <div v-if="pickupMethod === 'delivery'" class="delivery-address">
          <el-input
              v-model="deliveryAddress"
              placeholder="请输入配送地址"
          ></el-input>
        </div>

        <div class="payment-method">
          <span>支付方式</span>
          <el-radio-group v-model="paymentMethod">
            <el-radio label="scan">扫码支付</el-radio>
            <el-radio label="cash">现金</el-radio>
            <el-radio label="card">卡内记账</el-radio>
          </el-radio-group>
        </div>

        <div class="payment-timer">
          <span>请在 {{ countdownMinutes }} 分 {{ countdownSeconds }} 秒 后完成支付，否则订单将自动取消</span>
        </div>

        <div class="checkout-summary">
          <div class="summary-item">
            <span>折扣金额：</span>
            <span>￥{{ discountAmount.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>订单编号：</span>
            <span>{{ generateOrderNumber() }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="checkoutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheckout">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";

export default {
  name: 'OrderSystem',
  setup() {
    // 当前激活的选项卡
    const activeTab = ref('order')

    // 点餐服务相关数据
    const mealGroups = ref([])
    const meals = ref([])
    // 加载分组数据
    const loadMealsGroup = () => {
      axios.get(BASE_URL + '/v1/mealsGroup/select?')
          .then((response) => {
            if (response.data.state == 2000) {
              mealGroups.value = response.data.data
            } else {
              ElMessage.error(response.data.msg)
            }
          })
    }
    const loadMeals = () => {
      axios.get(BASE_URL + '/v1/meals/select?')
          .then((response) => {
            if (response.data.state == 2000) {
              meals.value = response.data.data
            } else {
              ElMessage.error(response.data.msg)
            }
          })
    }

    onMounted(() => {
      loadMealsGroup();
      loadMeals();
    })

    const currentCategory = ref('1')
    const searchKeyword = ref('')
    const currentScreen = ref(0)



    // 购物车相关
    const cart = ref([])
    const orderRemark = ref('')

    // 订单列表相关
    const orderStatus = ref('new')
    const orders = ref([
      {
        id: '1',
        orderNumber: 'DD20230606175013',
        status: 'new',
        meals: [
          { dish: { id: '1', name: '玉米炖排骨', price: 30.00 }, quantity: 1 },
          { dish: { id: '2', name: '川香辣子鸡', price: 45.00 }, quantity: 1 },
          { dish: { id: '8', name: '紫菜蛋花汤', price: 10.00 }, quantity: 1 }
        ],
        totalQuantity: 3,
        pickupMethod: 'dineIn',
        deliveryAddress: '',
        paymentMethod: 'scan',
        totalAmount: 85.00,
        discountAmount: 0.00,
        actualAmount: 85.00,
        orderTime: '2023-06-06 15:20:30',
        remark: '少放辣椒'
      },
      {
        id: '2',
        orderNumber: 'DD20230606175014',
        status: 'new',
        meals: [
          { dish: { id: '1', name: '玉米炖排骨', price: 30.00 }, quantity: 1 },
          { dish: { id: '2', name: '川香辣子鸡', price: 45.00 }, quantity: 1 },
          { dish: { id: '8', name: '紫菜蛋花汤', price: 10.00 }, quantity: 1 }
        ],
        totalQuantity: 3,
        pickupMethod: 'delivery',
        deliveryAddress: '康复一区1102号60床号',
        paymentMethod: 'scan',
        totalAmount: 85.00,
        discountAmount: 0.00,
        actualAmount: 85.00,
        orderTime: '2023-06-06 15:20:30',
        remark: '少放辣椒'
      }
    ])

    // 下单结账相关
    const checkoutDialogVisible = ref(false)
    const pickupMethod = ref('dineIn')
    const deliveryAddress = ref('')
    const paymentMethod = ref('scan')
    const countdown = ref(180) // 3分钟倒计时
    let countdownTimer = null

    // 计算属性
    const filteredDishes = computed(() => {
      let result = meals.value.filter(dish => dish.groupId === currentCategory.value)

      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(dish => dish.name.toLowerCase().includes(keyword))
      }

      return result
    })

    const totalQuantity = computed(() => {
      return cart.value.reduce((total, item) => total + item.quantity, 0)
    })

    const totalAmount = computed(() => {
      return cart.value.reduce((total, item) => total + (item.dish.price * item.quantity), 0)
    })

    const discountAmount = computed(() => {
      // 这里可以根据业务逻辑计算折扣金额
      return 0
    })

    const filteredOrders = computed(() => {
      return orders.value.filter(order => order.status === orderStatus.value)
    })

    const currentTime = computed(() => {
      const now = new Date()
      return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
    })

    const countdownMinutes = computed(() => {
      return Math.floor(countdown.value / 60)
    })

    const countdownSeconds = computed(() => {
      return countdown.value % 60
    })

    // 方法
    const prevScreen = () => {
      currentScreen.value = Math.max(0, currentScreen.value - 1)
    }

    const nextScreen = () => {
      currentScreen.value += 1
    }

    const scrollUp = () => {
      // 实现滚动逻辑
    }

    const scrollDown = () => {
      // 实现滚动逻辑
    }

    const handleSearch = () => {
      // 搜索逻辑
    }

    const handleSearchClear = () => {
      searchKeyword.value = ''
    }

    const addToCart = (dish) => {
      const existingItem = cart.value.find(item => item.dish.id === dish.id)

      if (existingItem) {
        existingItem.quantity += 1
      } else {
        cart.value.push({
          dish,
          quantity: 1
        })
      }
    }

    const removeFromCart = (index) => {
      cart.value.splice(index, 1)
    }

    const increaseQuantity = (index) => {
      cart.value[index].quantity += 1
    }

    const decreaseQuantity = (index) => {
      if (cart.value[index].quantity > 1) {
        cart.value[index].quantity -= 1
      } else {
        removeFromCart(index)
      }
    }

    const clearCart = () => {
      cart.value = []
    }

    const showCheckoutDialog = () => {
      checkoutDialogVisible.value = true
      startCountdown()
    }

    const startCountdown = () => {
      countdown.value = 180
      clearInterval(countdownTimer)

      countdownTimer = setInterval(() => {
        countdown.value -= 1

        if (countdown.value <= 0) {
          clearInterval(countdownTimer)
          checkoutDialogVisible.value = false
          ElMessage.warning('订单已超时取消')
        }
      }, 1000)
    }

    const generateOrderNumber = () => {
      const now = new Date()
      return `DD${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`
    }

    const confirmCheckout = () => {
      const newOrder = {
        id: String(orders.value.length + 1),
        orderNumber: generateOrderNumber(),
        status: 'new',
        meals: [...cart.value],
        totalQuantity: totalQuantity.value,
        pickupMethod: pickupMethod.value,
        deliveryAddress: deliveryAddress.value,
        paymentMethod: paymentMethod.value,
        totalAmount: totalAmount.value,
        discountAmount: discountAmount.value,
        actualAmount: totalAmount.value - discountAmount.value,
        orderTime: currentTime.value,
        remark: orderRemark.value
      }

      orders.value.push(newOrder)
      cart.value = []
      orderRemark.value = ''
      checkoutDialogVisible.value = false
      clearInterval(countdownTimer)

      ElMessage.success('下单成功')
    }

    const cancelOrder = (orderId) => {
      const index = orders.value.findIndex(order => order.id === orderId)
      if (index !== -1) {
        orders.value[index].status = 'cancelled'
        ElMessage.success('订单已取消')
      }
    }

    const acceptOrder = (orderId) => {
      const index = orders.value.findIndex(order => order.id === orderId)
      if (index !== -1) {
        orders.value[index].status = 'preparing'
        ElMessage.success('已接单')
      }
    }

    const getStatusText = (status) => {
      const statusMap = {
        new: '待制作',
        preparing: '制作中',
        delivering: '配送中',
        completed: '已完成',
        pendingPayment: '待支付',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    }

    const getPaymentMethodText = (method) => {
      const methodMap = {
        scan: '微信扫码支付',
        cash: '现金',
        card: '卡内记账'
      }
      return methodMap[method] || method
    }

    const formatDishes = (meals) => {
      return meals.map(item => `${item.dish.name}*${item.quantity}`).join('、')
    }

    // 生命周期
    onMounted(() => {
      // 初始化数据
    })

    onUnmounted(() => {
      clearInterval(countdownTimer)
    })

    return {
      activeTab,
      mealGroups,
      currentCategory,
      searchKeyword,
      currentScreen,
      meals,
      filteredDishes,
      cart,
      orderRemark,
      totalQuantity,
      totalAmount,
      discountAmount,
      orderStatus,
      orders,
      filteredOrders,
      checkoutDialogVisible,
      pickupMethod,
      deliveryAddress,
      paymentMethod,
      countdownMinutes,
      countdownSeconds,
      currentTime,
      prevScreen,
      nextScreen,
      scrollUp,
      scrollDown,
      handleSearch,
      handleSearchClear,
      addToCart,
      removeFromCart,
      increaseQuantity,
      decreaseQuantity,
      clearCart,
      showCheckoutDialog,
      confirmCheckout,
      cancelOrder,
      acceptOrder,
      getStatusText,
      getPaymentMethodText,
      formatDishes,
      generateOrderNumber
    }
  }
}
</script>

<style scoped>
.order-system {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.header h1 {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
}

.main-tabs {
  margin-top: 15px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.order-service {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.order-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-panel {
  display: flex;
  width: 70%;
  border-right: 1px solid #eee;
}

.category-list {
  width: 150px;
  padding: 10px;
  border-right: 1px solid #eee;
  overflow-y: auto;
}

.category-item {
  padding: 10px;
  margin-bottom: 5px;
  cursor: pointer;
  border-radius: 4px;
}

.category-item:hover {
  background-color: #f5f5f5;
}

.category-item.active {
  background-color: #409eff;
  color: white;
}

.dish-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 10px;
  overflow: hidden;
}

.search-bar {
  margin-bottom: 10px;
}

.screen-control {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.screen-number {
  margin: 0 10px;
}

.meals {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.dish-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.dish-info {
  display: flex;
  flex-direction: column;
}

.dish-name {
  font-weight: bold;
}

.dish-price {
  color: #f56c6c;
}

.right-panel {
  width: 30%;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.selected-meals {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #eee;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dish-cart {
  flex: 1;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.cart-dish-info {
  flex: 1;
}

.cart-dish-price {
  margin: 0 10px;
  color: #f56c6c;
}

.cart-dish-actions {
  display: flex;
}

.order-summary {
  padding-top: 10px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.dish-remark {
  margin: 10px 0;
}

.checkout-btn {
  width: 100%;
  margin-top: 10px;
}

.order-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.order-tabs {
  margin-bottom: 10px;
}

.orders {
  flex: 1;
  overflow-y: auto;
}

.order-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.order-status {
  color: #f56c6c;
}

.order-meals{
  margin-bottom: 10px;
}

.order-details {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.detail-item {
  margin-right: 20px;
  margin-bottom: 5px;
}

.order-amount {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.amount-item {
  margin-right: 20px;
  margin-bottom: 5px;
}

.order-remark {
  margin-bottom: 10px;
  color: #666;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.checkout-dialog {
  padding: 10px;
}

.pickup-method,
.payment-method {
  margin: 15px 0;
}

.delivery-address {
  margin: 10px 0;
}

.payment-timer {
  margin: 15px 0;
  color: #f56c6c;
  text-align: center;
}

.checkout-summary {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
</style>